from django.contrib.auth import authenticate
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from django.contrib.auth.models import User

# from demo_app.serializers import sss

# class yyy(ModelViewSet):
#     queryset = xxx.objects.all()
#     serializer_class = sss
from demo_app.models import Goods, Order, Comment
from demo_app.serializers import GoodsSerializer, OrderWriteSerializer, OrderReadSerializer, CommentSerializer


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        user = authenticate(request, username=username, password=password)

        if user:
            # 登录成功
            return Response({'code': '0', 'msg': '登录成功', 'uid': user.id, 'username': user.username})
        else:
            return Response({'code': '999', 'msg': '登录失败'})


class GoodsModelViewSet(ModelViewSet):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer


class CommentModelViewSet(ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer


class OrderModelViewSet(ModelViewSet):
    queryset = Order.objects.all()
    # serializer_class = OrderSerializer

    filter_fields = ('user',)

    def get_serializer_class(self, *args, **kwargs):
        if (self.action == 'create'):
            return OrderWriteSerializer
        return OrderReadSerializer
